package cn.goour.web.sys.controller

import cn.goour.web.base.entity.Msg
import cn.goour.web.sys.entity.Admin
import cn.goour.web.sys.entity.type.HttpHeader
import cn.goour.web.sys.service.AdminService
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Controller
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.ResponseBody
import setAdmin
import javax.annotation.PostConstruct
import javax.servlet.http.HttpServletRequest

@Controller
open class AdminLoginController {

    @Autowired
    private lateinit var adminService: AdminService

    @GetMapping("/adminLogin")
    open fun index() = "web/admin/login"

    @ResponseBody
    @PostMapping(value = "/adminLogin", params = arrayOf("username", "password"), headers = arrayOf(HttpHeader.Ajax))
    open fun login(admin: Admin, request: HttpServletRequest): Msg {
        val msg = try {
            val result = adminService.getLogin(admin)
            request.setAdmin(result)
            Msg("登录成功")
        } catch (e: Exception) {
            Msg.error(e)
        }
        return msg
    }

    init {
        logger.info("Initialized ${this.javaClass.simpleName}...")
    }

    @PostConstruct
    open fun post() {
        logger.info("PostConstruct ${this.javaClass.simpleName}...")
    }

    companion object {
        private val logger = LoggerFactory.getLogger(AdminLoginController::class.java)
    }
}